package com.mcookie.app.minicompo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class MiniCompoActivity extends Activity {
    /** Called when the activity is first created. */
	
	MiniCompoView mcv;
	com.mcookie.app.minicompo.MiniCompoView mcvf;
	
	RadioGroup rg;
	 
	PopupWindow pw_load;
	View pv_lod;
	
	TextView pop_tv;
	
	public static Blur BlurStyle = null;
	public static int BlurSize = 20;
	
	static int loadMode = 0;
	
	final int CV_REQUESTCODE_BRUSH = 11;
	final int CV_REQUESTCODE_LOAD = 15;
	
	final int LD_REQUESTCODE_CAMERA = 151;
	final int LD_REQUESTCODE_ALBUM = 152;
	final int LD_REQUESTCODE_CROP = 153;

	final int CV_REQUESTCODE_SAVE_CROP = 16;
	
	private Uri mImageCaptureUri;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        
        File Directory = new File("/sdcard/minicompo/");
		if (!Directory.isDirectory()) {
			Directory.mkdirs();
		}
        
		mcv = new MiniCompoView(this);        
        mcvf = (com.mcookie.app.minicompo.MiniCompoView)findViewById(R.id.miniCompoView1);
        
        rg = (RadioGroup)findViewById(R.id.rg1);
        rg.setOnCheckedChangeListener(OCCL);
        
        pv_lod = View.inflate(this, R.layout.load_dialog, null);
        pw_load = new PopupWindow(pv_lod, 480, 800);
        
        Button camera = (Button)pv_lod.findViewById(R.id.ld_camera_bt);
        Button album = (Button)pv_lod.findViewById(R.id.ld_album_bt);
        Button cansel = (Button)pv_lod.findViewById(R.id.ld_cancel_bt);
        
        camera.setOnClickListener(OnClick);
        album.setOnClickListener(OnClick);
        cansel.setOnClickListener(OnClick);
        
        
        Button load = (Button)findViewById(R.id.bt_load);
        load.setOnClickListener(OnClick);
        
        Button save = (Button)findViewById(R.id.bt_save);
        save.setOnClickListener(OnClick);
        
        Button brush = (Button)findViewById(R.id.bt_brush);
        brush.setOnClickListener(OnClick);
        
        pop_tv = (TextView)pv_lod.findViewById(R.id.ld_title);
       
    }
    
    
    
    OnClickListener OnClick = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.bt_load:
				
				pw_load.showAtLocation(pv_lod, Gravity.CENTER, 0, 0);
				
				break;
				
			case R.id.bt_save:
				
				ImageCrop(CV_REQUESTCODE_SAVE_CROP, saveAction());
				
				break;
				
			case R.id.bt_brush:
				
				Intent intent = new Intent(MiniCompoActivity.this, BrushEditerDialog.class);
				startActivityForResult(intent, CV_REQUESTCODE_BRUSH);
				
				break;
				
			case R.id.ld_camera_bt:
				cameraIntent();
				break;
				
			case R.id.ld_album_bt:
				albumIntent();
				break;
				
			case R.id.ld_cancel_bt:
				pw_load.dismiss();
				break;
				
			

			}
			
		}
	};
    

	OnCheckedChangeListener OCCL = new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			// TODO Auto-generated method stub
			if(checkedId == R.id.rb_move){
				mcv.pdfxChange(null);
				mcv.modeChange(100);
			}
			
			if(checkedId == R.id.rb_erase){
				mcv.pdfxChange(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
				mcv.modeChange(101);
			}
		}
	};
	
	/**
	 * 세이브 버튼이 눌렸을때 동작. 임시파일을 만들어서 sd에 temp.png라는 이름으로 저장한다.
	 * 이후 리턴에서 FileToContent 메소드를 실행하여 컨텐트 uri로 주소를 바꾸어 반환한다.
	 */
	public Uri saveAction(){
		
		mcvf.setDrawingCacheEnabled(true);
		Bitmap bm = null;  
		
		bm = mcvf.getDrawingCache();
		
		String mPath = Environment.getExternalStorageDirectory().getAbsolutePath();
		String fullPath = mPath + "/minicompo/" + "temp.png";
		//�ӽ������н�.
		File fileCacheItem = new File(fullPath);
    	OutputStream out = null;

    	try
    	{
    		fileCacheItem.createNewFile();
    		out = new FileOutputStream(fileCacheItem);
    		            
    		bm.compress(CompressFormat.PNG, 100, out);
    	}
    	catch (Exception e) 
    	{
    		e.printStackTrace();
    	}
    	finally
    	{
    		try
    		{
    			out.close();
    		}
    		catch (IOException e)
    		{
    			e.printStackTrace();
    		}
    	}
    	
    	Toast.makeText(MiniCompoActivity.this, "임시파일 저장.", Toast.LENGTH_LONG).show();
		
    	return FileToContent("/minicompo/temp.png"); 
	}
	
	
	/**
	 * file uri를 content uri로 변경한다..
	 * @param filename. 파일이 특정 폴더에 들어있다면 /특정폴더/test.png 식으로 넣어야한다.
	 * @return content uri로 변경하여 반환.
	 */
	public Uri FileToContent(String filename){
		Log.e("june", "filename : " + filename);
		Uri contentURI = null;
		
		//file uri 앞에 붙게될 경로를 시스템으로부터 받아온다.
		Uri fileURI = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), filename));
		String filePath = fileURI.getPath();
		
    	Cursor c = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
    			null, "_data = '" + filePath + "'", null, null);
    	c.moveToNext();
    	int id = c.getInt(0);
    	
    	contentURI = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
    	Log.e("june", "contentURI : " + contentURI);

    	return contentURI;
	}
	
	
	/**
	 * 카메라 인텐트.
	 */
	public void cameraIntent(){
		Log.i("LoadDialog", "cameraIntent. 카메라에서 이미지를 가져옵니다.");
		
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		
		//임시파일 생성.
		String uri = "temp_" + String.valueOf(System.currentTimeMillis()) + ".png";
		mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), uri));
		
		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
		startActivityForResult(intent, LD_REQUESTCODE_CAMERA);
		overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
		
	}
	
	/**
	 * 엘범인텐트.
	 */
	public void albumIntent(){
		
		Log.i("LoadDialog", "albumIntent 로부터 이미지를 가져옵니다.");
		
		Intent intent = new Intent(Intent.ACTION_PICK);
		
		intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
		intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
		
		startActivityForResult(intent, LD_REQUESTCODE_ALBUM);
		overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
	}
	
	/**
	 * 이미지 잘라내기. 함께 온 코드번호에 따라 잘라내는 이미지의 크기가 달라진다. 
	 * @param requstCode
	 */
	public void ImageCrop(int requstCode, Uri uri){
		Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        
        if(requstCode == CV_REQUESTCODE_SAVE_CROP){
        	intent.putExtra("outputX", 500);
        	intent.putExtra("outputY", 500);
        } else {
        	intent.putExtra("outputX", 300);
        	intent.putExtra("outputY", 300);
        }
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, requstCode);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		
		
		
		case LD_REQUESTCODE_CAMERA:
			if(resultCode == RESULT_OK){
				ImageCrop(LD_REQUESTCODE_CROP, mImageCaptureUri);
			} else {
				Toast.makeText(MiniCompoActivity.this, "LD_REQUESTCODE_CAMERA 카메라로부터 이미지를 가져오는데 실패했습니다.", Toast.LENGTH_SHORT).show();
			}
			break;
		case LD_REQUESTCODE_ALBUM:
			if(resultCode == RESULT_OK){
				Log.d("LoadDialog", "LD_REQUESTCODE_ALBUM 엘범으로부터 이미지를 가져왔습니다.");
				
				mImageCaptureUri = data.getData();
				
				Log.d("june", "mImageUri : " + mImageCaptureUri);
				ImageCrop(LD_REQUESTCODE_CROP, mImageCaptureUri);
				
			} else {
				Toast.makeText(MiniCompoActivity.this, "LD_REQUESTCODE_ALBUM 엘범에서 이미지를 가져오는데 실패했습니다.", Toast.LENGTH_SHORT).show();
			}

			break;
			
			
			
		case LD_REQUESTCODE_CROP:
			if(resultCode == RESULT_OK){
				
				final Bundle extras = data.getExtras();
				Bitmap photo = null;
		        if(extras != null)
		        {
		          photo = extras.getParcelable("data");
		        }
		  
		        File f = new File(mImageCaptureUri.getPath());
		        if(f.exists())
		        {
		          f.delete();
		        }
		        
		        if(loadMode == 0){
		        	
		        	mcv.baseBitmap = Bitmap.createScaledBitmap(photo, 500, 500, true);

		        	loadMode = 1;
		        	pop_tv.setText("compo Image Load");
		        } else {
		        	
		        	Bitmap aa = Bitmap.createScaledBitmap(photo, 300, 300, true);
		        	mcv.setCompoImage(aa);
		        	
		        	mcv.scale = 1;
		        	loadMode = 0;
		        	pop_tv.setText("base Image Load");
		        }
		        
	        	if(photo == null){
	        		Log.d("june", "photo == null");
//	        		returnValue(RESULT_CANCELED);
	        	} else {
//	        		returnValue(RESULT_OK);
	        	}
		        
		         
			} else {
				Toast.makeText(MiniCompoActivity.this, "LD_REQUESTCODE_CROP 이미지 잘라내기 실패.", Toast.LENGTH_SHORT).show();
			}
			break;
			
			
			
		case CV_REQUESTCODE_SAVE_CROP:
			if(resultCode == RESULT_OK){
				
				final Bundle extras = data.getExtras();
				Bitmap photo = null;
		        if(extras != null)
		        {
		          photo = extras.getParcelable("data");
		        }
		        
		        String mPath = Environment.getExternalStorageDirectory().getAbsolutePath();
				String fullPath = mPath + "/minicompo/" + System.currentTimeMillis() + ".png";

				File fileCacheItem = new File(fullPath);
		    	OutputStream out = null;

		    	try
		    	{
		    		fileCacheItem.createNewFile();
		    		out = new FileOutputStream(fileCacheItem);
		    		            
		    		photo.compress(CompressFormat.PNG, 100, out);
		    	}
		    	catch (Exception e) 
		    	{
		    		e.printStackTrace();
		    	}
		    	finally
		    	{
		    		try
		    		{
		    			out.close();
		    		}
		    		catch (IOException e)
		    		{
		    			e.printStackTrace();
		    		}
		    	}
		    	
		    	//갤러리 갱신.
		    	sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
		    			Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
				
		        
			} else {
				Toast.makeText(MiniCompoActivity.this, "이미지 잘라내기 실패.", Toast.LENGTH_LONG).show();
			}
			
			
			break;
			
			
			
		case CV_REQUESTCODE_BRUSH:
			if(resultCode == RESULT_OK){
				
				Log.d("CPV", "CV_REQUESTCODE_BRUSH 브러쉬 전환.");
				
				int brushSize = data.getIntExtra("brushSize", -1);
				String blurStyle = data.getStringExtra("blurStyle");
				String erase = data.getStringExtra("erase");
				
				Log.d("CPV", "CV_REQUESTCODE_BRUSH 리턴받은 브러쉬정보 : " 
						+ "brushSize : " + brushSize + ", "
						+ "blurStyle : " + blurStyle + ", "
						+ "erase : " + erase);
				
				BlurSize = brushSize;
				
				if(blurStyle.equals("normal")){
					BlurStyle = Blur.NORMAL;
				} else {
					BlurStyle = null;
				}
				
//				mcv.invalidate();
				
				mcv.setErasePaint(BlurStyle);
				
			} else {
				Log.d("CPV", "CV_REQUESTCODE_BRUSH 브러쉬 정보리턴 실패.");
			}
			break;
		}
		
		
	}
	
	
	

	
	
}